<?php

namespace App\System\Fina\Repositories;

use App\Module\Api\Controllers\Request\TableRequest;
use App\Module\Api\Controllers\Request\TableWhereRequest;
use App\System\Base\Helpers\Traits\SinglePattern;
use App\System\Base\Repositories\Repository;
use App\System\Cis\Model\CisBankAccount;
use App\System\Cis\Model\CisUser;
use App\System\Cis\Repositories\CisUserRepository;
use App\System\Fina\Model\FinaIntegralRegRecord;
use App\System\Log\Repositories\LogAdminRepository;
use Illuminate\Support\Facades\DB;


class FinaIntegralRegRecordRepository extends Repository
{
    use SinglePattern;

    /**
     * @param string $record_type 1 积分 2 注册币
     * @param string $status
     * @param string $keyword
     * @param string $start_time
     * @param string $end_time
     * @param string $type 财务类型
     * @param string $pay_type
     * @param bool $getall false：分页 true：不分页
     * @param int $user_id
     * @param int $beDeal 是否待结算
     * @return mixed
     */
    public function getList($record_type='',$status='',$keyword='',$start_time='',$end_time='',$type='',$pay_type='',$getall=false,$user_id=0,$beDeal=0){
        if($getall){
            $data = FinaIntegralRegRecord::with(['user','pay'])
                ->when($record_type, function ($query) use ($record_type) {
                    return $query->where('record_type', $record_type);
                })
                ->when($status, function ($query) use ($status) {
                    return $query->where('status', $status);
                })
                ->when($keyword,function($query)use($keyword){
                    return $query->whereHas('user',function ($query) use ($keyword){
                        $query->where('id',$keyword);
                    });
                })
                ->when($start_time,function ($query)use($start_time){
                    return $query->where('created_at','>=',$start_time);
                })
                ->when($end_time,function ($query)use($end_time){
                    return $query->where('created_at','<=',$end_time.' 23:59:59');
                })
                ->when($type, function ($query) use ($type) {
                    return $query->where('type', $type);
                })
                ->when($pay_type,function($query)use($pay_type){
                    return $query->whereHas('pay',function ($query) use ($pay_type){
                        $query->where('payment_type',$pay_type);
                    });
                })
                ->when($user_id, function ($query) use ($user_id) {
                    return $query->where('user_id', $user_id);
                })
                ->when($beDeal, function ($query) use ($beDeal) {
                    return $query->where('status', '!=',1);
                })
                ->orderBy('id', 'desc')
                ->get();
        }else{
            $data = FinaIntegralRegRecord::with(['user','pay'])
                ->when($record_type, function ($query) use ($record_type) {
                    return $query->where('record_type', $record_type);
                })
                ->when($status, function ($query) use ($status) {
                    return $query->where('status', $status);
                })
                ->when($keyword,function($query)use($keyword){
                    return $query->whereHas('user',function ($query) use ($keyword){
                        $query->where('id',$keyword);
                    });
                })
                ->when($start_time,function ($query)use($start_time){
                    return $query->where('created_at','>=',$start_time);
                })
                ->when($end_time,function ($query)use($end_time){
                    return $query->where('created_at','<=',$end_time.' 23:59:59');
                })
                ->when($type, function ($query) use ($type) {
                    return $query->where('type', $type);
                })
                ->when($pay_type,function($query)use($pay_type){
                    return $query->whereHas('pay',function ($query) use ($pay_type){
                        $query->where('payment_type',$pay_type);
                    });
                })
                ->when($user_id, function ($query) use ($user_id) {
                    return $query->where('user_id', $user_id);
                })
                ->when($beDeal, function ($query) use ($beDeal) {
                    return $query->where('status', '!=',1);
                })
                ->orderBy('id', 'desc')
                ->paginate();
        }
        foreach ($data as $k=>$v){
            $v->bank = json_decode($v->bank_info,true);
        }
        return $data;
    }

    /**
     * @param $id
     * @param $updata
     * @return array|bool
     */
    public function editData($id,$updata)
    {
        if(!$id){
            return false;
        }
        DB::beginTransaction();
        $finaInte = FinaIntegralRegRecord::find($id);
        $finaInte->status = $updata['status'];
        $finaInte->reasons = $updata['reasons']??'';
        $bool1 = $finaInte->save();
        $bool2 = true;
        $cisUser = CisUserRepository::getInstance();
        if($finaInte->type == 7 && $finaInte->status==2){
            $bool2 = $cisUser->updateUserPurse($finaInte->user_id,1,'integral',$finaInte->cash+$finaInte->commossion);
//            $userInfo = CisUser::where('id',$finaInte->user_id)->first();
//            $bool2 = CisUser::where('id',$finaInte->user_id)->incrementing(['integral'=>($finaInte->cash+$finaInte->commission+$userInfo->integral)]);
        }
        if($finaInte->type == 6 && $finaInte->status == 2){
            //$userInfo = CisUser::find($finaInte->user_id);
            if($finaInte->record_type==1){
                $bool2 = $cisUser->updateUserPurse($finaInte->user_id,2,'freeze_integral',$finaInte->cash);
//                $bool2 = CisUser::where('id',$finaInte->user_id)->update(['freeze_integral'=>($userInfo->freeze_integral-$finaInte->cash)]);
            }else{
                $bool2 = $cisUser->updateUserPurse($finaInte->user_id,2,'freeze_registered_currency',$finaInte->cash);
//                $bool2 = CisUser::where('id',$finaInte->user_id)->update(['freeze_registered_currency'=>($userInfo->freeze_registered_currency-$finaInte->cash)]);
            }
        }
        if($bool1 && $bool2){
            $bool = true;
            $msg = '操作成功！';
            DB::commit();
        }else{
            $bool = false;
            $msg = '操作失败！';
            DB::rollBack();
        }
        return ['data'=>$bool,'message'=>$msg];
    }

    /**
     * @param $ids
     * @param $updata
     * @return array|bool
     */
    public function editDatas($ids,$updata)
    {
        if(!$ids){
            return false;
        }
        DB::beginTransaction();
        $bool1 = FinaIntegralRegRecord::whereIn('id',$ids)->update($updata);
        $datas  = FinaIntegralRegRecord::with(['user'])->whereIn('id',$ids)->get();
        $bool2 = true;
        foreach ($datas as $v){
            if($v->type == 7 && $v->status==2){
                $bool2 = CisUser::where('id',$v->user_id)->update(['integral'=>($v->cash+$v->user['integral'])]);
            }
            //var_dump($bool2);
            if($v->type == 6 && $v->status == 2){
                if($v->record_type==1){
                    $bool2 = CisUser::where('id',$v->user_id)->update(['freeze_integral'=>($v->user['freeze_integral']-$v->cash)]);
                }else {
                    $bool2 = CisUser::where('id', $v->user_id)->update(['freeze_registered_currency' => ($v->user['freeze_registered_currency'] - $v->cash)]);
                }
            }
        }
        if($bool1 && $bool2){
            $bool = true;
            $msg = '操作成功！';
            $data['type'] = 1;
            $data['log_info'] = '批量处理待结算积分，注册币';
            $logAdmin = LogAdminRepository::getInstance();
            $logAdmin->saveAdminLog($data);
            DB::commit();
        }else{
            $bool = false;
            $msg = '操作失败！';
            DB::rollBack();
        }
        return ['data'=>$bool,'message'=>$msg];
    }

    /**
     * 生成财务数据
     * @param array $data 数据数组
     * @param integer $user_id 用户id
     * @return bool|mixed
     * @author  liujun
     */
    public function createFina(array $data,$user_id=null)
    {
        $data['trade_no'] = date("YmdHis").mt_rand(100000,999999);
        if(!isset($data['remark_info'])){      //手机端申请提现微信号存在备注字段,2017-12-27 by Hjj
            $data['remark_info'] = $this->generationDescription($data,$user_id);
        }
        $res = FinaIntegralRegRecord::create($data);
        if(!$res)
        {
            return false;
        }
        return $res->id;
    }

    /**
     * 生成描述
     * @param array $data
     * @param integer $user_id 受到关联的用户ID，非当前用户ID
     * @return string
     * @author liujun
     */
    public function generationDescription($data,$user_id=null)
    {
        $currency_array = [1=>'积分',2=>'注册币'];
        $income_array = [1=>'收入',2=>'支出'];
        $currency = $currency_array[$data['record_type']];
        $income = $income_array[$data['income']];
        $description = [
            1=>'充值'.$income.$data['cash'].$currency,
            2=>'订单'.$income.$data['cash'].$currency,
            3=>$user_id.'向您的账号转入'.$data['cash'].$currency,
            4=>'转出'.$data['cash'].$currency.'给'.$user_id,
            5=>'报单'.$income.$data['cash'].$currency,
            6=>'日工资'.$income.$data['cash'].$currency,
            7=>'申请提现'.$income.$data['cash'].$currency,
            8=>'管理奖'.$income.$data['cash'].$currency,
            9=>'企业推荐奖励'.$income.$data['cash'].$currency,
            10=>'积分转注册币：'.$currency.$income.$data['cash'],
            11=>'资金调节'.$currency.$income.$data['cash'],
            12=>'服务奖励：创客ID为'.$user_id,
            13=>'复消'.$income.$data['cash'].$currency
        ];
        return $description[$data['type']];
    }

    public function fundAdjustment(array $data)
    {
        if(!$data){
            return false;
        }
        DB::beginTransaction();
        $bool1 = true;
        if($data['integral_number']){
            if($data['integral_type']==1){
                $res1 = CisUser::where('id',$data['user_id'])->increment('integral',$data['integral_number']);
                $inteUpdata['income'] = 1;
            }else{
                $res1 = CisUser::where('id',$data['user_id'])->decrement('integral',$data['integral_number']);
                $inteUpdata['income'] = 2;
            }
            $userInfo = CisUser::where('id',$data['user_id'])->first();
            $inteUpdata['type'] = 11;
            $inteUpdata['record_type'] = 1;
            $inteUpdata['cash'] = $data['integral_number'];
            $inteUpdata['after_cash'] = $userInfo['integral'];
            $inteUpdata['commission'] = 0;
            $inteUpdata['status'] = 1;
            $inteUpdata['admin_id'] = \Session::get('adminid');
            $inteUpdata['user_id'] = $data['user_id'];
            $inteUpdata['reasons'] = $data['reasons'];
            $res2 = $this->createFina($inteUpdata);
            if(!$res1 || !$res2){
                $bool1 = false;
            }
        }
        $bool2 = true;
        if($data['coin_number']){
            if($data['coin_type']==1){
                $res3 = CisUser::where('id',$data['user_id'])->increment('registered_currency',$data['coin_number']);
                $inteUpdata['income'] = 1;
            }else{
                $res3 = CisUser::where('id',$data['user_id'])->decrement('registered_currency',$data['coin_number']);
                $inteUpdata['income'] = 2;
            }
            $userInfo = CisUser::where('id',$data['user_id'])->first();
            $inteUpdata['type'] = 11;
            $inteUpdata['record_type'] = 2;
            $inteUpdata['cash'] = $data['coin_number'];
            $inteUpdata['after_cash'] = $userInfo['registered_currency'];
            $inteUpdata['commission'] = 0;
            $inteUpdata['status'] = 1;
            $inteUpdata['admin_id'] = \Session::get('adminid');
            $inteUpdata['user_id'] = $data['user_id'];
            $inteUpdata['reasons'] = $data['reasons'];
            $res4 = $this->createFina($inteUpdata);
            if(!$res3 || !$res4){
                $bool2 = false;
            }
        }
        if($bool1 && $bool2){
            $bool = true;
            $msg = '操作成功！';
            DB::commit();
        }else{
            $bool =false;
            $msg = '操作失败！';
            DB::rollBack();
        }
        return ['data'=>$bool,'message'=>$msg];
    }

    /**
     * 获取前天待结算的记录
     * @param 结束时间 格式年月日(2018-01-01)
     * @return object
     */
    public function getUnsettledFinance($end_time)
    {
        $data = FinaIntegralRegRecord::with(['user'=>function($select){$select->select(['id','integral','registered_currency']);}])
            ->select(['id','type','record_type','cash','user_id'])
            ->where('status',3)
            ->where('type',6)
            ->when($end_time,function ($query)use($end_time){
                return $query->where('created_at','<=',$end_time.' 23:59:59');
            })
            ->get();
        return $data;
    }

    /**
     * 更新财务信息
     */
    public function updateFina($data,$id)
    {
        if(!$id)
        {
            return false;
        }

        $res = FinaIntegralRegRecord::find($id);
        foreach ($data as $k=>$v)
        {
            $res->$k = $v;
        }
        $res = $res->save();
        return $res;
    }

    /**
     *API 获取财务记录列表
     */
    public function getApiList(TableRequest $request,TableWhereRequest $tableWhereRequest,$record_type,$user_id)
    {
        $status = $tableWhereRequest->status;
        $data = FinaIntegralRegRecord::with(['user'])
            ->where("user_id",$user_id)
            ->when($record_type,function($query) use($record_type){
            $query->where('record_type',$record_type);
            })
            ->when($status,function($query) use($status){
                $query->where('status',$status);
            })
            ->orderBy($request->orderBy,$request->orderType)
            ->paginate($request->limit,['*'],'page',$request->page);
        foreach($data as $v) {
            $item = [];
            $item['id'] = $v->id;
            $item['amount'] = $v->cash;
            $item['type'] = $v->income;
            $item['description'] = $v->remark_info;
            $item['balance'] = $v->after_cash;
            $item['batch'] = $v->trade_no;
            $item['userName'] = $v->user->name ? $v->user->mobile.'('.$v->user->name.')' : $v->user->mobile;
            $item['timestamp'] = $v->updated_at->toDateTimeString();
            $return['records'][] = $item;
        }
        $return['total'] =$data->total();
        return $return;
    }

    /**
     * 获取一条用户的订单财务
     * @param $order_id
     * @param $user_id
     * @return bool
     * @author liujun
     */
    public function getOrderFina($order_id,$user_id)
    {
        if(!$order_id || !$user_id) return false;
        return FinaIntegralRegRecord::with(['pay'])
        ->where("order_id",$order_id)->where("user_id",$user_id)->first();
    }

    /**
     * 根据orderID，状态查询一条订单ID用积分支付记录财务记录
     * @param $order_id
     * @param $status
     * @param $type
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    public function getOneByOrderId($order_id,$status,$type)
    {
        return FinaIntegralRegRecord::where('order_id',$order_id)->where('status',$status)->where("type",$type)->first();
    }


    /**
     * 通过支付记录查找记录
     * @param $pay_id
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    public function getOneByPayId($pay_id)
    {
        return FinaIntegralRegRecord::where('pay_id',$pay_id)->first();
    }

    /**
     * 财务更新，自定义条件更新
     * @param $set array 要更新的数据
     * @param $where array 更新条件 ['field'=>'字段','value'=>'值']
     * @return bool
     */
    public function customUpdate($set,$where)
    {
        if(!$set || !$where)
        {
            return false;
        }
        $res = FinaIntegralRegRecord::where($where['field'],$where['value'])->update($set);
        return $res;
    }

    /**
     * 硬删除财务记录（请勿使用此方法）
     */
    public function deleteFina($user_id)
    {
        if(!$user_id)
        {
            return false;
        }
       return FinaIntegralRegRecord::where('user_id',$user_id)->forceDelete();
    }
}